package models

import (
	"t11Lib/t11Errors"
	"t11Lib/t11Model"
)

type Gateway struct {
	t11Model.BaseMdl
	UserId string //一个网关只能有一个管理员，分享是基于设备的，而非网关
}

type gatewayDao struct{}

var GatewayDao gatewayDao

//创建或更新
func CreateOrUpdate(conn *t11Model.DbConn, obj interface{}, keys ...string) (bool, t11Errors.T11Error) {
	ret := false
	return ret, t11Model.Transacrtion(conn, func() t11Errors.T11Error {
		cnt, err := conn.Update(obj, keys...)
		if err != nil {
			return t11Errors.Wrap(err)
		}
		if cnt != 0 {
			return nil
		}
		//创建用户
		_, er := conn.Insert(obj)
		return t11Errors.Wrap(er)
	})
}

func (self gatewayDao) CreateOrUpdateGateway(conn *t11Model.DbConn, gwId string, user *JwtToken) (bool, t11Errors.T11Error) {
	g := &Gateway{}
	g.Id = gwId
	g.UserId = user.ToId()
	return CreateOrUpdate(conn, g, "UserId")
}

func (self gatewayDao) GetAllGatewayIds(conn *t11Model.DbConn) ([]string, t11Errors.T11Error) {
	var ids []string
	_, err := conn.Ormer.Raw("select id from gateway").QueryRows(&ids)
	return ids, t11Errors.Wrap(err)
}

func (self gatewayDao) SetGatewayUser(conn *t11Model.DbConn, gwId string, userId string) t11Errors.T11Error {
	g := &Gateway{}
	g.Id = gwId
	g.UserId = userId
	_, e := conn.Update(g, "UserId")
	return t11Errors.Wrap(e)
}

func (self gatewayDao) GetGatewaysByUser(conn *t11Model.DbConn, user *JwtToken) ([]*Gateway, t11Errors.T11Error) {
	var ret []*Gateway
	_, e := conn.QueryTable(&Gateway{}).Filter("UserId", user.ToId()).All(&ret)
	return ret, t11Errors.Wrap(e)
}

func (self gatewayDao) GetById(conn *t11Model.DbConn, gwId string) (*Gateway, t11Errors.T11Error) {
	ret := &Gateway{}
	ret.Id = gwId
	e := conn.Read(ret)
	return ret, t11Errors.Wrap(e)
}
